/**
 * moieo.net
 * @author Moieo
 */
package cn.moieo.carcontrol

import android.content.pm.ActivityInfo
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableDoubleStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import cn.moieo.carcontrol.payload.LeftRockerControl
import cn.moieo.carcontrol.payload.RightRockerControl
import cn.moieo.carcontrol.ui.theme.CarControlTheme
import cn.moieo.carcontrol.view.Direction
import cn.moieo.carcontrol.view.DirectionMode
import cn.moieo.carcontrol.view.RockerView
import cn.moieo.carcontrol.view.StateView

// 起始编号
const val START_ID = 0xF4

class MainActivityViewModel : androidx.lifecycle.ViewModel() {
    // 左侧摇杆角度
    var leftRockerAngle by mutableDoubleStateOf(0.0)

    // 左侧摇杆速度
    var leftRockerLevel by mutableIntStateOf(0)

    // 左侧摇杆方向
    var leftRockerDirection by mutableStateOf(Direction.CENTER)

    // 左摇杆控制
    private val leftRockerControl: LeftRockerControl = LeftRockerControl()

    // 右侧摇杆角度
    var rightRockerAngle by mutableDoubleStateOf(0.0)

    // 右侧摇杆速度
    var rightRockerLevel by mutableIntStateOf(0)

    // 右摇杆控制
    private val rightRockerControl: RightRockerControl = RightRockerControl()

    // 右侧摇杆方向
    var rightRockerDirection by mutableStateOf(Direction.CENTER)

    // 连接状态
    var connectState by mutableStateOf(ConnectionState.WAITING_CONNECT)

    // tcpServer
    private val server =
        TCPServer(port = 8888, onConnectionListener = object : TCPServer.OnConnectionListener {
            override fun onConnectionStateChanged(state: TCPServer.ConnectionState) {
                when (state) {
                    is TCPServer.ConnectionState.Connected -> {
                        connectState = ConnectionState.CONNECTED
                    }

                    is TCPServer.ConnectionState.Disconnected -> {
                        connectState = ConnectionState.DISCONNECTED
                    }

                    else -> {}
                }
            }
        })

    override fun onCleared() {
        super.onCleared()
        server.stop()
    }

    fun leftControlMotor() {
        leftRockerControl.controlMotor(
            server,
            leftRockerDirection,
            leftRockerLevel,
            leftRockerAngle
        )
    }

    fun rightControlMotor() {
        rightRockerControl.controlMotor(
            server,
            rightRockerDirection,
            rightRockerLevel,
            rightRockerAngle
        )
    }

    enum class ConnectionState {
        CONNECTED,
        DISCONNECTED,
        WAITING_CONNECT
    }
}

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            MainActivityContent()
        }
    }
}

/**
 * 虚拟手柄
 */
@Composable
fun VirtualRocker(
    modifier: Modifier = Modifier,
    directionMode: DirectionMode = DirectionMode.DIRECTION_8,
    onAngleChanged: (Double) -> Unit = {},
    onDistanceLevelChanged: (Int) -> Unit = {},
    onDirectionChanged: (Direction) -> Unit = {}
) {
    Box(modifier = modifier, contentAlignment = Alignment.Center) {
        RockerView(
            rockerColor = Color(0xFFCCCCCC).copy(alpha = 0.5f),
            areaColor = Color.Gray.copy(alpha = 0.5f),
            directionMode = directionMode,
            onAngleChanged = onAngleChanged,
            onDirectionChanged = onDirectionChanged,
            onDistanceLevelChanged = onDistanceLevelChanged
        )
    }
}

/**
 * 状态指示器
 */
@Composable
fun ConnectState(
    modifier: Modifier = Modifier,
    viewMode: MainActivityViewModel
) {
    Column(modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally) {
        // 状态图标
        Row(modifier = Modifier.padding(10.dp)) {
            StateView(
                size = 22.dp,
                transparent = 0.6f,
                text = viewMode.leftRockerAngle.toInt().toString(),
                fontSize = 8.sp,
                fontColor = Color.White,
                color = Color.Gray
            )

            StateView(
                size = 22.dp,
                transparent = 0.6f,
                flash = viewMode.connectState == MainActivityViewModel.ConnectionState.WAITING_CONNECT,
                color = when (viewMode.connectState) {
                    MainActivityViewModel.ConnectionState.WAITING_CONNECT -> Color.White
                    MainActivityViewModel.ConnectionState.CONNECTED -> Color.Green
                    MainActivityViewModel.ConnectionState.DISCONNECTED -> Color.Red
                }
            )

            StateView(
                size = 22.dp,
                transparent = 0.6f,
                text = viewMode.rightRockerAngle.toInt().toString(),
                fontSize = 8.sp,
                fontColor = Color.White,
                color = Color.Gray
            )
        }
    }
}

// 主界面
@Composable
fun MainView(viewModel: MainActivityViewModel) {
    Row(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 左侧手柄
        VirtualRocker(
            modifier = Modifier.weight(0.8f),
            directionMode = DirectionMode.DIRECTION_2_VERTICAL,
            onAngleChanged = { angle ->
                viewModel.leftRockerAngle = angle
            },
            onDirectionChanged = { direction ->
                viewModel.leftRockerDirection = direction
                viewModel.leftControlMotor()
            },
            onDistanceLevelChanged = { level ->
                viewModel.leftRockerLevel = level
                viewModel.leftControlMotor()
            })

        ConnectState(
            modifier = Modifier
                .weight(1f)
                .fillMaxHeight(),
            viewModel
        )

        // 右侧手柄
        VirtualRocker(
            modifier = Modifier.weight(0.8f),
            directionMode = DirectionMode.DIRECTION_2_HORIZONTAL,
            onAngleChanged = { angle ->
                viewModel.rightRockerAngle = angle
            },
            onDirectionChanged = { direction ->
                viewModel.rightRockerDirection = direction
                viewModel.rightControlMotor()
            },
            onDistanceLevelChanged = { level ->
                viewModel.rightRockerLevel = level
                viewModel.rightControlMotor()
            })
    }
}

@Preview(showBackground = true, device = "spec:width=540dp,height=1200dp,orientation=landscape")
@Composable
fun MainActivityContent(viewModel: MainActivityViewModel = viewModel<MainActivityViewModel>()) {
    val context = LocalContext.current
    LaunchedEffect(Unit) {
        val activity: ComponentActivity = context as ComponentActivity
        activity.requestedOrientation =
            ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE // 强制横屏
        FullScreenUtils.fullScreen(activity) // 隐藏状态栏
    }
    CarControlTheme {
        MainView(viewModel)
        // Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->  }
    }
}